
// 导入 jsonwebtoken
const jwt = require('jsonwebtoken')
// 导入数据库操作器
const { UserModel } = require('../db/model')
// 导入配置信息
const { secret, expires } = require('../config')

// 登录操作
const login = async (req, res) => {

  const { username, password } = req.body

  const result = await UserModel.findOne({ username, password })

  if (!result) return res.send({ code: 0, message: '登录失败' })

  const token = 'Bearer ' + jwt.sign({ id: result._id }, secret, { expiresIn: expires })

  res.send({
    code: 1,
    message: '登录成功',
    token,
    user_id: result._id
  })
}

// 获取用户个人信息
const info = async (req, res) => {
  const { id } = req.params

  // 根据 id 获取个人信息
  const result = await UserModel.findById(id)

  // 返回给前端
  res.send({
    code: 1,
    message: '获取个人信息成功',
    info: {
      id: result._id,
      nickname: result.nickname,
      username: result.username,
      age: result.age,
      gender: result.gender,
      avatar: result.avatar,
      desc: result.desc
    }
  })
}

module.exports = {
  login,
  info
}
